package com.atguigu.web;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        //获取验证码
        String token = (String)request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        request.removeAttribute(KAPTCHA_SESSION_KEY);
        //检查验证码是否正确 验证码为:abcde
        if(token.equalsIgnoreCase(code)&&token !=null){
            //正确-->保存到数据库-->跳到注册成功页面register_success.html
            if(userService.existsUsername(username)){
                //用户名不可用-->跳回注册页面
                //把回显信息保存到Request中
                request.setAttribute("msg","用户名已存在!");
                request.setAttribute("username",username);
                request.setAttribute("email",email);

                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }else{
                //用户名可用-->保存到数据库
                userService.registerUser(new User(null,username,password,email));
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            }

        }else{
            //不正确-->跳回注册页面
            //把回显信息保存到Request中
            request.setAttribute("msg","验证码错误!");
            request.setAttribute("username",username);
            request.setAttribute("email",email);

            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
